/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/binary-tree-tilt
   @Language: C++
   @Datetime: 19-05-15 17:32
   */

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
	int postorder(TreeNode *root, int &diff){
		if(root==NULL) return 0;
		int left=postorder(root->left,diff);
		int right=postorder(root->right,diff);
		diff+=abs(left-right);
		return root->val+left+right;
	}
public:
	/**
	 * @param root: the root
	 * @return: the tilt of the whole tree
	 */
	int findTilt(TreeNode * root) {
		// Write your code here
		int diff=0;
		postorder(root,diff);
		return diff;
	}
};
